package com.woniuxy.house.web;

import com.woniuxy.house.entity.*;
import com.woniuxy.house.service.MessageService;
import com.woniuxy.house.service.UserService;
import com.woniuxy.house.utils.JwtUtil;
import com.woniuxy.house.utils.PhoneMessgeUtil;
import com.woniuxy.house.vo.*;
import javafx.geometry.Pos;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author baobo
 * @date 2022-08-29-10:42
 */
@RestController
@RequestMapping("/api")
public class UserController {
	@Autowired
	private UserService userService;
	@Value("${house.defaultphoto}")
	private String defaultPhoto;
	@Autowired
	private JwtUtil jwtUtil;
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	@RequestMapping(value = "/regist",produces = {"application/json;charset=UTF-8"})
	public ResponseEntity regist(@RequestBody @Valid User user){
		//无上传头像默认头像
		if(user.getHeadPhoto()==null||"null".equals(user.getHeadPhoto())||"".equals(user.getHeadPhoto())){
			user.setHeadPhoto(defaultPhoto);
			user.setOtherAccount("。。。");
			user.setUserSign(".");
		}
		User regist = userService.regist(user);
		regist.setPassword(null);
		return new ResponseEntity("200","注册成功",user);
	}

	///**
	// * 通过用户id初始化个人中心
	// * @param id
	// * @return
	// */
	//@RequestMapping("/user/initmine")
	//public ResponseEntity initMine( Integer id){
	//	return new ResponseEntity("200","success",userService.getUsrById(id));
	//}

	/**
	 * 修改用户信息,传入需要修改的内容及用户id
	 * @param user
	 * @return
	 */
	@RequestMapping("/user/update")
	public ResponseEntity update( @RequestBody User user){

		//解析出id
		String jwt=(String)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		user.setId((Integer)jwtUtil.verifyJWTGetUserId(jwt,"id"));
		return new ResponseEntity("200","修改成功",userService.update(user));
	}

	/**
	 * 发送短信确认码
	 * @param userRestPassWrodVo
	 * @return
	 */
	@RequestMapping("/sendphonemsg")
	public ResponseEntity sendPhoneMsg(@RequestBody @Valid UserRestPassWrodVo userRestPassWrodVo,HttpServletRequest request){
		//检查用户电话和账号是否正确
		userService.checkUserWithPhone(userRestPassWrodVo.getAccount(), userRestPassWrodVo.getPhoneNumber());
		//生成随机短信码
		Random random = new Random();
		int i1 = random.nextInt(10);
		int i2= random.nextInt(10);
		int i3 = random.nextInt(10);
		int i4 = random.nextInt(10);
		String code=""+i1+i2+i3+i4;
		//存储到redis
		String phnoeKey= UUID.randomUUID().toString();
		stringRedisTemplate.opsForValue().set(phnoeKey,code,60, TimeUnit.SECONDS);
		//发送到手机
		PhoneMessgeUtil.sendMsg(code);
		return new ResponseEntity("200","发送成功",phnoeKey);
	}
	/**
	 * 修改密码
	 * @param userRestPassWrodVo
	 * @return
	 */
	@RequestMapping("/resetpassword")
	public ResponseEntity resetPassword(@RequestBody @NotNull UserRestPassWrodVo userRestPassWrodVo, HttpServletRequest request){
		String userCode=userRestPassWrodVo.getCode();
		//从redis取电话验证码
		String code = stringRedisTemplate.opsForValue().get("phoneKey");
		if(code==null){
			new ResponseEntity("500","错误码",null);
		}
		User newUser=null;
		if(userCode.equals(code)){
			//修改密码
			User user=new User();
			user.setAccount(userRestPassWrodVo.getAccount());
			user.setPassword(userRestPassWrodVo.getPassword());
			newUser=userService.resetPassword(user);
		}
		return new ResponseEntity("200","发送成功",null);
	}

	/**
	 * 获取个人信息
	 *
	 * @return
	 */
	@PreAuthorize("hasAuthority('all')")
	@RequestMapping(value="/user/getuserinfo",produces = {"application/json;charset=UTF-8"})
	@ResponseBody
	public ResponseEntity getUserInfo(){
		String jwt=(String)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		User user = userService.getUsrById((Integer)jwtUtil.verifyJWTGetUserId(jwt,"id"));
		return new ResponseEntity("200","初始化成功",user);
	}

	/**
	 * 获取个人房源预约信息
	 *
	 * @return
	 */
	@PreAuthorize("hasAuthority('all')")
	@RequestMapping(value="/user/getuserbookings",produces = {"application/json;charset=UTF-8"})
	@ResponseBody
	public ResponseEntity getUserBookings(@Min(Integer.MIN_VALUE)Integer p){

		String jwt=(String)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		PageBean<List<Booking>> bookings = userService.getUserBookings((Integer) jwtUtil.verifyJWTGetUserId(jwt, "id"),p!=null?p:1);
		return new ResponseEntity("200","初始化成功",bookings);
	}

	/**
	 * 获取个人房源帖子列表
	 *
	 * @return
	 */
	@PreAuthorize("hasAuthority('all')")
	@RequestMapping(value="/user/getuserposts",produces = {"application/json;charset=UTF-8"})
	@ResponseBody
	public ResponseEntity getUserPosts(@Min(Integer.MIN_VALUE)Integer p){
		String jwt=(String)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		PageBean<List<Post>> bookings = userService.getUserPosts((Integer) jwtUtil.verifyJWTGetUserId(jwt, "id"),p!=null?p:1);
		return new ResponseEntity("200","初始化成功",bookings);
	}

	/**
	 * 获取个人房源帖子列表
	 *
	 * @return
	 */
	@PreAuthorize("hasAuthority('all')")
	@RequestMapping(value="/user/getusersource",produces = {"application/json;charset=UTF-8"})
	@ResponseBody
	public ResponseEntity getUserSource(@Min(Integer.MIN_VALUE)Integer p){
		String jwt=(String)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		PageBean<List<Source>> source = userService.getUserSources((Integer) jwtUtil.verifyJWTGetUserId(jwt, "id"),p!=null?p:1);
		return new ResponseEntity("200","初始化成功",source);
	}

	/**
	 * 获取个人单个房源的信息
	 *
	 * @return
	 */
	@PreAuthorize("hasAuthority('all')")
	@RequestMapping(value="/user/getusersourceone",produces = {"application/json;charset=UTF-8"})
	@ResponseBody
	public ResponseEntity getUserSourceOne(@Min(Integer.MIN_VALUE)Integer id){
		Source source = userService.getSourceById(id);
		return new ResponseEntity("200","初始化成功",source);
	}

	/**
	 * 删除用户的帖子
	 *
	 * @return
	 */
	@PreAuthorize("hasAuthority('all')")
	@RequestMapping(value="/user/deleteuserpost",produces = {"application/json;charset=UTF-8"})
	@ResponseBody
	public ResponseEntity deleteUserPost(@Min(Integer.MIN_VALUE) Integer id){
		String jwt=(String)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		//通过userid和postid删除post
		Integer userId=(Integer) jwtUtil.verifyJWTGetUserId(jwt, "id");

		userService.deleteUserPost(userId,id);

		return new ResponseEntity("200","删除",null);
	}
	/**
	 * 获取消息历史记录
	 *
	 * @return
	 */
	@PreAuthorize("hasAuthority('all')")
	@RequestMapping(value="/user/gethistory",produces = {"application/json;charset=UTF-8"})
	@ResponseBody
	public ResponseEntity getHistory(@Min(Integer.MIN_VALUE)Integer id){
		//通过两用户的id获取聊天记录

		String jwt=(String)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		//通过userid和postid删除post
		Integer userId=(Integer) jwtUtil.verifyJWTGetUserId(jwt, "id");
		List<Message> history = userService.getHistory(userId, id);

		return new ResponseEntity("200","获取消息历史记录",history);
	}
	/**
	 * 获取消息列表
	 *
	 * @return
	 */
	@PreAuthorize("hasAuthority('all')")
	@RequestMapping(value="/user/getmessagelist",produces = {"application/json;charset=UTF-8"})
	@ResponseBody
	public ResponseEntity getMessageList(){
		//通过两用户的id获取聊天记录
		String jwt=(String)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		//通过userid和postid删除post
		Integer userId=(Integer) jwtUtil.verifyJWTGetUserId(jwt, "id");
		List<List<Message>> messageList = userService.getMessageList(userId);
		return new ResponseEntity("200","获取消息列表成功",messageList);
	}
	/**
	 * 修改房源信息
	 *
	 * @return
	 */
	@PreAuthorize("hasAuthority('all')")
	@RequestMapping(value="/user/updatesource",produces = {"application/json;charset=UTF-8"})
	@ResponseBody
	public ResponseEntity getMessageList(@RequestBody @NotNull AddSourceVo addSourceVo){
		//通过两用户的id获取聊天记录
		String jwt=(String)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		//通过userid和postid删除post
		Integer userId=(Integer) jwtUtil.verifyJWTGetUserId(jwt, "id");
		userService.updateSourceOne(addSourceVo,userId);

		return new ResponseEntity("200","修改成功",null);
	}

	/**
	 * 更新房源
	 * @return
	 */
	@PreAuthorize("hasAuthority('all')")
	@ResponseBody
	@RequestMapping("/user/updatesource")
	public ResponseEntity updateSource(@RequestBody @NotNull AddSourceVo addSourceVo) {
		String jwt=(String)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		//通过userid和postid删除post
		Integer userId=(Integer) jwtUtil.verifyJWTGetUserId(jwt, "id");
		userService.updateSourceOne(addSourceVo,userId);
		return ResponseEntity.SUCCESS;
	}

	/**
	 * 删除房源
	 * @param id
	 * @return
	 */

	@PreAuthorize("hasAuthority('all')")
	@ResponseBody
	@RequestMapping("/user/deletesource")
	public ResponseEntity deleteSource(@Min(Integer.MIN_VALUE) Integer id) {
		String jwt=(String)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		//通过userid和postid删除post
		Integer userId=(Integer) jwtUtil.verifyJWTGetUserId(jwt, "id");
		userService.deleteSourceOne(userId,id);
		return ResponseEntity.SUCCESS;
	}

	/**
	 * 查询用户的帖子详情
	 * @param id
	 * @return
	 */
	@PreAuthorize("hasAuthority('all')")
	@ResponseBody
	@RequestMapping("/user/getpostone")
	public ResponseEntity getPostOne(@Min(Integer.MIN_VALUE)Integer id) {
		String jwt=(String)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		//通过userid和postid删除post
		Integer userId=(Integer) jwtUtil.verifyJWTGetUserId(jwt, "id");
		Post postOne = userService.getPostOne(userId, id);
		return  new ResponseEntity("200","查询成功",postOne);
	}

	/**
	 * 修改求租帖子
	 * @param post
	 * @param request
	 * @return
	 */
	@RequestMapping("/user/updatepostqiu")
	public ResponseEntity updatePostQiu(@RequestBody Post post, HttpServletRequest request){
		String jwt= request.getHeader("jwt");
		Integer id=(Integer)jwtUtil.verifyJWTGetUserId(jwt,"id");
		userService.updatePostQiu(id,post);
		return ResponseEntity.SUCCESS;
	}

	/**
	 * 删除预约信息
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping("/user/deleteuserbooking")
	public ResponseEntity deleteUserBooking(@Min(Integer.MIN_VALUE)Integer id, HttpServletRequest request){
		String jwt= request.getHeader("jwt");
		Integer uid=(Integer)jwtUtil.verifyJWTGetUserId(jwt,"id");
		userService.deleteUserBooking(uid,id);
		return ResponseEntity.SUCCESS;
	}


	/**
	 * 修改密码
	 * @param userVo
	 * @param request
	 * @return
	 */
	@RequestMapping("/user/updateuserpassword")
	public ResponseEntity deleteUserBooking(@RequestBody @Valid UserVo userVo, HttpServletRequest request){

		String jwt= request.getHeader("jwt");
		Integer uid=(Integer)jwtUtil.verifyJWTGetUserId(jwt,"id");
		userService.updateUserPassword(uid,userVo);
		return ResponseEntity.SUCCESS;
	}
}
